/**
 * 依赖全局变量 InfoGlobal
 * Created by shopnc on 2015/11/26.
 */
//定义表格
var dtGridColumns = [
    {
        id: 'delFlag',
        type: 'int',
        hideQuery:true,
        'export':false,
        hideQueryType:'eq',
        hideQueryValue:1,
        hide:true
    },
    {
        id: 'name',
        title: '代理商名称',
        type: 'string',
        headerClass: 'text-center',
        columnClass: 'text-center',
        fastSort: false,
        fastQuery: true,
        fastQueryType: 'eq'
    },
    {
        id: 'code',
        title: '代理商编号',
        type: 'string',
        fastSort: false,
        fastQuery: true,
        fastQueryType: 'eq'
    },
    {
        id: 'feeRate',
        type: 'string',
        title: '手续费分成比例',
        headerClass: 'text-center',
        columnClass: 'text-center',
        fastSort: false
    },
    {
        id: 'overnightRate',
        type: 'string',
        title: '过夜费分成比例',
        headerClass: 'text-center',
        columnClass: 'text-center',
        fastSort: false
    },
    {
        id: 'loseRate',
        type: 'string',
        title: '亏损分成比例',
        headerClass: 'text-center',
        columnClass: 'text-center',
        fastSort: false
    },
    {
        id: 'loseIsOpen',
        title: '是否收取亏损分成',
        type: 'string',
        fastSort: false,
        codeTable: {
            1: $lang.isOpen.T1,
            2: $lang.isOpen.T2,
        }
    },
    {
        id: 'status',
        title: '状态',
        type: 'string',
        headerClass: 'text-center',
        columnClass: 'text-center',
        fastSort: false,
        fastQuery: false,
        codeTable: {
            1: $lang.agentStatus.T1,
            2: $lang.agentStatus.T2,
        }
    },
    {
        id: 'account',
        title: '账户余额',
        type: 'number',
        headerClass: 'text-center',
        columnClass: 'text-center',
        fastSort: false,
        fastQuery: false
    },
    {
        id: 'operation',
        title: '管理操作',
        type: 'string',
        columnClass: 'text-center width-250',
        fastSort: false,
        extra: false,
        resolution: function (value, record, column, grid, dataNo, columnNo) {
            var html = "";
            var len = record.code.split(".").length;
            html += '<div class="btn-group">' +
                '<a href="javascript:;" data-toggle="dropdown" aria-expanded="false" class="btn btn-primary btn-sm dropdown-toggle m-r-10">' +
                '<i class="fa fa-gears"></i>&nbsp;操作&nbsp;' +
                '<span class="caret"></span></a><ul class="dropdown-menu dropdown-menu-left">';
            if ($("#agentEdit") && $("#agentEdit").val() == 1) {
                html += "<li><a href='#editModal' data-no='" + dataNo + "' data-toggle='modal'><i class='fa fa-lg fa-pencil-square m-r-10' ></i>&nbsp;编辑</a></li>";
            }
            if ($("#agentNext") && $("#agentNext").val() == 1) {
                if (len < 3) {
                    html += '<li><a href="#addModal" data-toggle="modal" title="新增下级代理商" data-no="' + dataNo + '"><i class="fa fa-lg fa-plus m-r-10"></i>新增下级代理商</a></li>';
                }
            }
            if ($("#agentRecharge") && $("#agentRecharge").val() == 1) {
                html += '<li><a href="#recharge" data-toggle="modal" title="入金" data-no="' + dataNo + '"><i class="fa fa-lg fa-plus m-r-10"></i>入金</a></li>';
            }
            if ($("#agentCash") && $("#agentCash").val() == 1) {
                html += '<li><a href="#cash" data-toggle="modal" title="出金" data-no="' + dataNo + '"><i class="fa fa-lg fa-plus m-r-10"></i>出金</a></li>';
            }
            html += '</ul></div>';
            if (len < 3) {
                html += '<a href="javascript:;" name="showChildren" data-dataNo="' + dataNo + '" class="btn btn-white btn-sm"><i class="fa fa-level-down"></i>下级代理商</a>';
            }

            // if ($("#agentNext") && $("#agentNext").val() == 1) {
            //     if(len < 3){
            //         html += "<a data-target='#addModal' class='btn btn-sm btn-info m-r-8' data-toggle='modal' data-no='" + dataNo + "' ><i class='fa fa-add'></i>&nbsp;新增下级代理商&nbsp;</a>";
            //     }
            // }
            // if ($("#agentEdit") && $("#agentEdit").val() == 1) {
            //     html += "<a data-target='#editModal' class='btn btn-sm btn-primary m-r-8' data-toggle='modal' data-no='" + dataNo + "' ><i class='fa fa-edit'></i>&nbsp;编辑&nbsp;</a>";
            // }
            // if ($("#agentRecharge") && $("#agentRecharge").val() ==1){
            //     html += "<a data-target='#recharge' class='btn btn-sm btn-success m-r-8' data-toggle='modal' data-no='" + dataNo + "'><i class='fa fa-add'></i>&nbsp;入金&nbsp;</a>";
            // }
            // if ($("#agentCash") && $("#agentCash").val() ==1){
            //     html += "<a data-target='#cash' class='btn btn-sm btn-warning m-r-8' data-toggle='modal' data-no='" + dataNo + "'><i class='fa fa-add'></i>&nbsp;出金&nbsp;</a>";
            // }
            // if ($("#agentDel") && $("#agentDel").val() == 1) {
            //     html += "<a href='javascript:;' class='btn btn-danger btn-sm m-r-8' onclick='information.delAgent(" + record.id + ",\"" + record.name + "\")'><i class='fa fa-trash-o'></i>&nbsp;删除&nbsp;</a>";
            // }

            return html;
        }
    }
];

var dtGridOption = {
    lang: 'zh-cn',
    ajaxLoad: true,
    loadURL: ncGlobal.adminRoot + 'agent/json/list',
    exportFileName: '代理商列表',
    columns: dtGridColumns,
    gridContainer: 'dtGridContainer',
    toolbarContainer: 'dtGridToolBarContainer',
    tools: 'refresh|faseQuery',
    pageSize: 10,
    pageSizeLimit: [10, 20, 50],
    ncColumnsType: {int:["status"],Timestamp: ["createTime"]},
    onGridComplete: function (grid) {
        var returnBtn = $("#returnParent"),
            parentInfo = menu.current.getParentInfo();
        //是否显示上一级
        if (parentInfo !== '') {
            //重新绑定事件
            returnBtn.removeClass("hidden").off("click")
                .on("click", function () {
                    menu.current.gridGoFormParentId(parentInfo.parentId);
                    //bycj[ 设置菜单信息 ]
                    menu.current.delList(parentInfo.level);
                });
        } else {
            returnBtn.addClass("hidden");
        }

        $("a[name='edit']").on('click', function () {
            var dataNo = $(this).attr("data-dataNo");
            $('a[data-toggle="modal"]').click();
        });

        /**
         * 查看下一级菜单按钮事件
         */
        $("a[name='showChildren']").on('click', function () {
            var dataNo = $(this).attr("data-dataNo");
            menuInfo = grid.exhibitDatas[dataNo];
            //bycj[ 设置菜单信息 ]
            menu.current.setList(menuInfo.level, menuInfo);
            menu.current.gridGoFormParentId(menuInfo.id);
        });
    }
};

var grid = $.fn.DtGrid.init(dtGridOption);
//排序
grid.sortParameter.columnId = ['desc_createTime'];
grid.fastQueryParameters = new Object();
grid.fastQueryParameters['eq_delFlag'] = 1;

/**
 * 自定义相关
 */
var menu = function ($) {
    /**
     *
     * @type {{}}
     */
    var current = {
        /**
         * 储存菜单列表
         */
        $$list: {},
        /**
         * 修改选择的菜单列表
         * @param level
         * @param obj
         */
        setList: function (level, obj) {
            level && obj && (this.$$list [level] = obj)
        },
        /**
         * 返回列表中指定层级的菜单
         * @param level
         * @returns {*}
         */
        getList: function (level) {
            return this.$$list [level];
        },
        /**
         * 删除
         * @param level
         */
        delList: function (level) {
            delete this.$$list[level];
        },
        /**
         * 获取当前所有 的菜单名字
         */
        getMenuInfo: function () {
            var r = '', n;
            for (n in this.$$list) {
                r += this.$$list[n].name + ' ';
            }
            return r;
        },
        /**
         * 获取上一级信息
         */
        getParentInfo: function () {
            var i = 5;
            while (i) {
                if (this.$$list.hasOwnProperty(i)) {
                    return this.$$list[i];
                }
                i--;
            }
            return '';
        },
        /**
         * 根据父级菜单id设置grid
         * @param parentId
         */
        gridGoFormParentId: function (parentId) {
            grid.fastQueryParameters = new Object();
            grid.fastQueryParameters['eq_delFlag'] = 1;
            grid.fastQueryParameters['eq_parentId'] = parentId;
            grid.pager.startRecord = 0;
            grid.pager.nowPage = 1;
            grid.pager.recordCount = -1;
            grid.pager.pageCount = -1;
            grid.refresh(true);
        }
    }



    //删除Url
    var delUrl = ncGlobal.adminRoot + "agent/json/del";

    function _delAgent(id, content) {
        var tpl = '您选择对代理商<strong>' + content + '</strong> 进行删除操作，删除后将无法恢复。<br/>您确定要进行删除操作吗?'
        $.ncConfirm({
            url: delUrl,
            data: {
                id: id
            },
            content: tpl,
            alertTitle: "删除操作"
        });
    }

    /**
     * 事件绑定
     * @private
     */
    function _bindEvent() {
        //模糊搜索
        $('#customSearch').click(function () {
            grid.fastQueryParameters = new Object();
            grid.fastQueryParameters['eq_delFlag'] = 1;
            grid.fastQueryParameters['lk_name_or_like_code'] = $('#keyword').val();
            grid.pager.startRecord = 0;
            grid.pager.nowPage = 1;
            grid.pager.recordCount = -1;
            grid.pager.pageCount = -1;
            grid.refresh(true);
        });

        //去除输入框回车键提交
        $("input").on("keydown", function (e) {
            if (e.keyCode == 13) {
                e.preventDefault();
                var a = $("#releasePrice");
                a.length && a.trigger("click");
            }
        });


        var addInfo = {
            initAddModal: function () {
                $addForm = $("#addForm");
                $(".alert-danger").remove();
                $addForm.psly().reset();
                $addForm.find('input[name="name"]').val("");
                $addForm.find('input[name="feeRate"]').val("");
                $addForm.find('input[name="overnightRate"]').val("");
                $addForm.find('input[name="loseRate"]').val("");
                $(".addLose").bootstrapSwitch('state', true);
                $(".addStatus").bootstrapSwitch('state', true);
            }
        }

        //新增代理商
        $('#addModal').on('show.bs.modal', function (event) {
            addInfo.initAddModal();
        });

        //编辑代理商
        $('#editModal').on('show.bs.modal', function (event) {
            //获取接受事件的元素
            var  button = $(event.relatedTarget),
                //获取data 参数
                datano = button.data('no'),
                modal = $(this),
                //获取列表框中的原始数据
                gridData = grid.sortOriginalDatas[datano],
                editForm = $("#editForm");
            //清除错误提示
            editForm.psly().reset();
            $(".alert-danger").remove();
            modal.find('input[name="id"]').val(gridData.id);
            $("#name").val(gridData.name);
            modal.find('input[name="overnightRate"]').val(gridData.overnightRate);
            modal.find('input[name="feeRate"]').val(gridData.feeRate);
            modal.find('input[name="loseRate"]').val(gridData.loseRate);
            if(gridData.loseIsOpen == 1){
                $(".editLose").bootstrapSwitch('state', true);
            }else{
                $(".editLose").bootstrapSwitch('state', false);
            }
            if(gridData.status == 1){
                $(".editStatus").bootstrapSwitch('state', true);
            }else{
                $(".editStatus").bootstrapSwitch('state', false);
            }
        });

        //代理商入金
        $('#recharge').on('show.bs.modal', function (event) {
            //获取接受事件的元素
            var  button = $(event.relatedTarget),
                //获取data 参数
                datano = button.data('no'),
                modal = $(this),
                //获取列表框中的原始数据
                gridData = grid.sortOriginalDatas[datano],
                rechargeForm = $("#rechargeForm");
            //清除错误提示
            rechargeForm.psly().reset();
            $(".alert-danger").remove();
            modal.find('input[name="id"]').val(gridData.id);
        });

        //代理商出金
        $('#cash').on('show.bs.modal', function (event) {
            //获取接受事件的元素
            var  button = $(event.relatedTarget),
                //获取data 参数
                datano = button.data('no'),
                modal = $(this),
                //获取列表框中的原始数据
                gridData = grid.sortOriginalDatas[datano],
                cashForm = $("#cashForm");
            //清除错误提示
            cashForm.psly().reset();
            $(".alert-danger").remove();
            modal.find('input[name="id"]').val(gridData.id);
        });

        //新增下级代理商
        $('#addModal').on('show.bs.modal', function (event) {
            //获取接受事件的元素
            var  button = $(event.relatedTarget),
                //获取data 参数
                datano = button.data('no'),
                modal = $(this),
                //获取列表框中的原始数据
                gridData = grid.sortOriginalDatas[datano],
                addForm = $("#addForm");
            var flag = "";
                if(gridData == null || gridData == '' || gridData == 'undefined'){
                    flag = "";
                }else{
                    flag = gridData.flag;
                }
            //清除错误提示
            addForm.psly().reset();
            $(".alert-danger").remove();
            modal.find('input[name="name"]').val("");
            modal.find('input[name="flag"]').val(flag);
            modal.find('input[name="feeRate"]').val("");
            modal.find('input[name="overnightRate"]').val("");
            modal.find('input[name="loseRate"]').val("");
            $(".addLose").bootstrapSwitch('state', true);
            $(".addStatus").bootstrapSwitch('state', true);
        });
    }

    //外部可调用
    return {
        init: function () {
            _bindEvent();
        },
        delAgent : _delAgent,
        current: current
    };
}(jQuery);
$(function () {
    grid.fastQueryParameters = new Object();
    grid.fastQueryParameters['eq_parentId'] = 0;
    grid.fastQueryParameters['eq_delFlag'] = 1;
    grid.load();
    menu.init();
    //绑定类型选择事件
    $("input[name=type]").click(function(){
        switch($(this).val()){
            case "0":
                $(".menuUrl").hide();
                $(".permission").hide();
                break;
            case "1":
                $(".menuUrl").show();
                $(".permission").show();
                break;
            default:
                $(".menuUrl").hide();
                $(".permission").show();
                break;
        }
    });
    $(".menuUrl").hide();
    $(".permission").hide();
})





